// https://www.lintcode.com/problem/binary-tree-maximum-path-sum/

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: An integer
     */
    public int maxPathSum(TreeNode root) {
        // write your code here
        ret = Integer.MIN_VALUE;
        _maxPathSum(root);
        return ret;
    }

    protected int _maxPathSum(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int lsum = _maxPathSum(root.left);
        int rsum = _maxPathSum(root.right);
        int smax = root.val + Math.max(lsum, rsum);
        smax = Math.max(smax, root.val);
        smax = Math.max(smax, root.val + lsum + rsum); // 包含当前节点的可能最大值
        if (smax > ret) {
            ret = smax;
        }
        return Math.max(root.val + Math.max(lsum, rsum), root.val); // 要考虑向上延伸
    }

    private int ret;
}